/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.utils;

import static com.huawei.housekeeper.common.constant.SecurityConstants.ISSUER;

import com.huawei.housekeeper.common.constant.CommonConstants;
import com.huawei.housekeeper.common.enums.AccountTypeEnum;
import com.huawei.housekeeper.common.utils.JwkUtil;
import com.huawei.housekeeper.dao.entity.User;
import com.huawei.saashousekeeper.config.TenantContext;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成jwt
 *
 * @author y00464350
 * @since 2022-02-11
 */
@Component
public class JwtGenerateTokenUtil {

    private static final String CLAIM_KEY_CREATED = "created";

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 根据用户信息生成token
     *
     * @param user 用户信息
     */
    public String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Claims.SUBJECT, user.getUserId());
        claims.put(CommonConstants.User.USER_NAME, user.getUserName());
        claims.put(CommonConstants.User.ROLE, AccountTypeEnum.ofAccountType(user.getAccountType()).get().getMessage());
        claims.put(CLAIM_KEY_CREATED, new Date(System.currentTimeMillis()));
        claims.put(CommonConstants.User.USER_DOMAIN, TenantContext.getDomain());
        return tokenHead + " " + Jwts.builder()
            .setClaims(claims)
            .setIssuer(ISSUER)
            .setSubject(ISSUER)
            .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
            .signWith(SignatureAlgorithm.RS256, JwkUtil.getPrivateKeyByJwk())
            .compact();
    }
}
